<template>
  <div class="container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-row>
          <el-col :span="6">
            <el-form-item label="老师姓名">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入老师姓名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="手机号">
              <el-input
                v-model="searchForm.phone"
                placeholder="请输入手机号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleResetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 列表 -->
    <div class="common-layout-main">
      <div class="common-head">
        <el-button type="primary" @click="handleAdd">添加老师</el-button>
      </div>
      <el-table :data="teachers" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="姓名" width="120"></el-table-column>
        <el-table-column
          prop="phone"
          label="手机号"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="subject"
          label="科目"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="200"
        ></el-table-column>
        <el-table-column
          prop="gmtCreate"
          label="创建时间"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="gmtModified"
          label="修改时间"
          width="180"
        ></el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 50, 100, 500]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchTeachers"
        @current-change="fetchTeachers"
      />
    </div>

    <!-- 编辑/添加弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form
        ref="formRef"
        :model="teacher"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="teacher.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="teacher.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="科目" prop="subject">
          <el-input v-model="teacher.subject" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="teacher.email" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { ref, reactive, onMounted } from "vue";
import { FormInstance } from "element-plus";
import {
  getTeacherList,
  getTeacherById,
  deleteTeacher,
  addTeacher,
  updateTeacher,
} from "@/api/teacher";
import { ElMessage, ElMessageBox } from "element-plus";

interface Teacher {
  id: string;
  name: string;
  phone: string; // 新增手机号
  subject: string; // 新增科目
  email: string; // 新增邮箱
}

interface SearchForm {
  name: string | null;
  teacherNumber: string | null;
}

interface Pagination {
  pageNum: number;
  pageSize: number;
  total: number;
}

export default {
  setup() {
    const teachers = ref<Teacher[]>([]);
    const teacher = reactive<Teacher>({
      id: "",
      name: "",
      phone: "",
      subject: "",
      email: "",
    });
    const searchForm = reactive<SearchForm>({
      name: null,
      teacherNumber: null,
    });
    const pagination = reactive<Pagination>({
      pageNum: 1,
      pageSize: 10,
      total: 0,
    });
    const dialogVisible = ref(false);
    const dialogTitle = ref("");

    const rules = reactive({
      name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
      phone: [
        { required: true, message: "手机号不能为空", trigger: "blur" },
        {
          pattern: /^[1][3-9][0-9]{9}$/,
          message: "手机号格式不正确",
          trigger: "blur",
        },
      ],
      subject: [{ required: true, message: "科目不能为空", trigger: "blur" }],
      email: [
        { required: true, message: "邮箱不能为空", trigger: "blur" },
        {
          type: "email",
          message: "邮箱格式不正确",
          trigger: ["blur", "change"],
        },
      ],
    });

    const formRef = ref<FormInstance | null>(null);
    const fetchTeachers = async () => {
      try {
        const response = await getTeacherList({ ...searchForm, ...pagination });
        teachers.value = response.data;
        pagination.total = response.total;
      } catch (error) {
        console.error("Error fetching teachers:", error);
      }
    };

    const handleAdd = () => {
      Object.assign(teacher, {
        id: "",
        name: "",
        phone: "",
        subject: "",
        email: "",
      });
      dialogTitle.value = "添加老师";
      dialogVisible.value = true;
    };

    const handleEdit = async (row: Teacher) => {
      const { data } = await getTeacherById(row.id);
      Object.assign(teacher, data);
      dialogTitle.value = "编辑老师";
      dialogVisible.value = true;
    };

    const handleDelete = async (id: string) => {
      try {
        await ElMessageBox.confirm("是否删除该老师？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        });
        await deleteTeacher(id);
        fetchTeachers();
        ElMessage({
          type: "success",
          message: "删除成功",
        });
      } catch (error) {
        console.error("Error deleting teacher:", error);
      }
    };

    const handleSubmit = async () => {
      formRef.value.validate(async (valid: boolean) => {
        if (valid) {
          try {
            if (teacher.id) {
              await updateTeacher(teacher);
              ElMessage({
                type: "success",
                message: "修改成功",
              });
            } else {
              await addTeacher(teacher);
              ElMessage({
                type: "success",
                message: "添加成功",
              });
            }
            fetchTeachers();
            dialogVisible.value = false;
          } catch (error) {
            console.error("Error saving teacher:", error);
          }
        } else {
          console.log("表单验证失败");
        }
      });
    };

    const handleSearch = () => {
      pagination.pageNum = 1;
      fetchTeachers();
    };

    const handleResetSearch = () => {
      Object.assign(searchForm, { name: null, teacherNumber: null });
      handleSearch();
    };

    onMounted(fetchTeachers);

    return {
      teachers,
      teacher,
      searchForm,
      dialogVisible,
      dialogTitle,
      pagination,
      rules,
      formRef,
      fetchTeachers,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSubmit,
      handleSearch,
      handleResetSearch,
    };
  },
};
</script>

<style lang="scss" scoped>
.container {
  .search-form {
    background: #fff;
    padding: 15px 10px 0;
    margin-bottom: 10px;
  }
  .common-layout-main {
    background-color: #fff;
    padding: 15px 10px 0;
  }
}
</style>
